import axios from 'axios'
import { TOKEN_UTILS } from '@/utils'
import { message } from 'antd'
import router from '@/routes/index.tsx'
import baseApiUrl from '../../config'
import { isMobile } from '@/utils'
const request = axios.create({
  baseURL: baseApiUrl.SQ_URL,
  timeout: 5000,
})
// console.log('baseApiUrl:', baseApiUrl.SQ_URL)
console.log('welcome！')
// 添加请求拦截器
request.interceptors.request.use(
  (config: any) => {
    // 在发送请求之前做些什么
    if (TOKEN_UTILS.getToken()) {
      config.headers.Authorization = TOKEN_UTILS.getToken()
    }
    return config
  },
  (error: any) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  (response: any) => {
    if (response.data.code === 400003) {
      TOKEN_UTILS.removeToken()
      if (!isMobile()) {
        router.navigate('/login')
      } else {
        router.navigate('/mobile/login')
      }
    }
    return response
  },
  (error: any) => {
    if (error.code === 'ERR_NETWORK') {
      return message.error('服务器异常')
    }
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)
export default request
